# main.py -- put your code here!
import machine 
import time
import network
import ujson

import micropython

from web.microdot import Microdot
import web.urequests as urequest

from tftlcd.ST7735 import TFT,TFTColor
from tftlcd.sysfont import sysfont

micropython.alloc_emergency_exception_buf(100)
'''
SCL -- SCK(18)
SDA -- MOSI(23)
RST -- RST(22)
DC  -- DC(21)
CS  -- 片选(19)
BLK -- 背光(5)
'''
tft_spi = machine.SPI(2,baudrate=20000000, polarity=0, phase=0, sck=machine.Pin(18), mosi=machine.Pin(23))

tft = TFT(tft_spi,dc=21,rst=22,cs=19,blk=5)
tft.initr()
tft.rgb(True)
tft.fill(TFT.BLACK)
tft.light(50)

#创建一个RTC对象
rtc = machine.RTC()
#设置当前的日期和时间
# rtc.datetime((2023,10,30,1,15,23,0,0))
# #获取当前的日期和时间
# dt = rtc.datetime()
# 获取当前时间
rtc.datetime()
year, month, day, week, hour, minute, second, _ = rtc.datetime()

# 打印当前时间
print("当前时间：{}-{}-{} {}:{}:{}".format(year, month, day, hour, minute, second))

# print('Date:%d-%d-%d' % (dt[0],dt[1],dt[2]))
# print('Time:%d-%d-%d' % (dt[4],dt[5],dt[6]))

# tft.text((1,1),"hello,welcome",TFT.YELLOW)
def ShowBMP(bmpStr):
    f=open(bmpStr, 'rb')
    if f.read(2) == b'BM':  #header
        dummy = f.read(8) #file size(4), creator bytes(4)
        offset = int.from_bytes(f.read(4), 'little')
        hdrsize = int.from_bytes(f.read(4), 'little')
        width = int.from_bytes(f.read(4), 'little')
        height = int.from_bytes(f.read(4), 'little')
        if int.from_bytes(f.read(2), 'little') == 1: #planes must be 1
            depth = int.from_bytes(f.read(2), 'little')
            if depth == 24 and int.from_bytes(f.read(4), 'little') == 0:#compress method == uncompressed
                print("Image size:", width, "x", height)
                rowsize = (width * 3 + 3) & ~3
                if height < 0:
                    height = -height
                    flip = False
                else:
                    flip = True
                w, h = width, height
                if w > 128: w = 128
                if h > 160: h = 160
                tft._setwindowloc((0,0),(w - 1,h - 1))
                for row in range(h):
                    if flip:
                        pos = offset + (height - 1 - row) * rowsize
                    else:
                        pos = offset + row * rowsize
                    if f.tell() != pos:
                        dummy = f.seek(pos)
                    for col in range(w):
                        bgr = f.read(3)
                        tft._pushcolor(TFTColor(bgr[2],bgr[1],bgr[0]))

#link wifi
def connect():
    led = machine.Pin(2,machine.Pin.OUT)
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    # print(wlan.scan())
    print(wlan.isconnected())
    if not wlan.isconnected():
        print("connecting to network...")
        led.value(1)
        wlan.connect('ChenTianYu_ WIFI','QW_183581er')
        while not wlan.isconnected():
            pass
    print("network config:",wlan.ifconfig())
    led.value(0)

ShowBMP('gdyg_fm.bmp')

time.sleep(5)

tft.fill(TFT.BLACK)
time.sleep(1)
ShowBMP('zsdfll_fm_120x160.bmp')

connect()
#web
app = Microdot()

@app.route('/')
def index(request):
    return 'Hello World!'

@app.route('/anime/gdyg')
def gdyg(request):
    r = urequest.get("http://114.115.168.109:8088/anime/gdyg")
    return ujson.loads(r.text)

@app.route("/anime/zsdfll")
def zsdfll(request):
    r = urequest.get("http://114.115.168.109:8088/anime/zsdfll")
    return ujson.loads(r.text)

app.run(host='0.0.0.0',port=5000,debug=False,ssl=None)

